﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ICDA.Web.Models;
using System.Data.Entity;
using ICDA.DataModel.Entities;
using ICDA.DataModel.Concrete;
using ICDA.DataModel.Abstract;
using System.IO;
using System.Drawing;

namespace ICDA.Web.Controllers
{
    public class AccountController : Controller
    {
        private static IRepository _repository;
        private static UserModel _userModel;
        public static UserModel userModel
        {
            get
            {
                if (_userModel == null)
                {
                    _userModel = new UserModel();
                }
                return _userModel;
            }
        }
        public static IRepository repository
        {
            get
            {
                if (_repository == null)
                {
                    _repository = new DBrepository();
                }
                return _repository;
            }
        }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    string encodedPassword= Helper.Encryption.Encode(model.Password);
                    var user = repository.users.FirstOrDefault(u => u.UserID.Trim() == model.UserName.Trim() && u.Status == true && u.Password.Trim() == encodedPassword);
                    if (user != null)
                    {
                        Session["UserName"] = user.Name.Trim();
                        Session["UID"] = user.UserID.Trim();
                        Session["user"] = user;
                        Session["Role"] = user.Role.Trim();
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("Error", "This login failed");
                        return View();
                    }
                }
                else
                {
                    return View(model);
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            Session.Clear();
            return RedirectToAction("LogOn", "Account");
        }

        public ActionResult MyAccount()
        {
            try
            {
                if (Session["UID"] != null)
                {
                    string uid = Session["UID"].ToString().Trim();
                    UserTables user = _repository.users.Where(u => u.UserID == uid).FirstOrDefault();
                    if (user != null)
                    {
                        userModel.Name = user.Name;
                        userModel.EmailID = user.EmailID;
                        userModel.SkillSets = user.Skills;
                        userModel.TeamName = user.TeamName;
                        userModel.DOB = user.DOB;
                        userModel.CSCJoiningDate = user.CSCJoiningDate;
                        userModel.ProjectJoiningDate = user.ProjectJoiningDate;
                        userModel.ManagerName = user.ManagerName;
                        userModel.Location = user.Location;
                        userModel.CUGNumber = user.ExtNumber;

                    }
                    return View(userModel);
                }
                else
                {
                    return RedirectToAction("LogOn", "Account");
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }
        public ActionResult ChangePassword()
        {
            if (Session["UID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(ChangePasswordModel viewModel)
        {
            try
            {
                string uid = Session["UID"].ToString().Trim();
                UserTables user = _repository.users.Where(u => u.UserID == uid).FirstOrDefault();
                if (user.Password == viewModel.OldPassword)
                {
                    user.Password = viewModel.NewPassword;
                }
                _repository.SaveChanges();
                return View();
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.InnerException.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        public ActionResult EditMyInfo()
        {
            try
            {
                if (Session["UID"] != null)
                {
                    string uid = Session["UID"].ToString().Trim();
                    UserTables user = _repository.users.Where(u => u.UserID == uid).FirstOrDefault();
                    if (user != null)
                    {
                        userModel.Name = user.Name;
                        userModel.EmailID = user.EmailID;
                        userModel.SkillSets = user.Skills;
                        userModel.TeamName = user.TeamName;
                        userModel.DOB = user.DOB;
                        userModel.CSCJoiningDate = user.CSCJoiningDate;
                        userModel.ProjectJoiningDate = user.ProjectJoiningDate;
                        userModel.ManagerName = user.ManagerName;
                        userModel.Location = user.Location;
                        userModel.CUGNumber = user.ExtNumber;
                    }
                    return View(userModel);
                }
                else
                {
                    return RedirectToAction("LogOn", "Account");
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.InnerException.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditMyInfo(UserModel viewModel)
        {
            try
            { 
                string uid = Session["UID"].ToString().Trim();
                UserTables user = _repository.users.Where(u => u.UserID == uid).FirstOrDefault();
                user.Name = viewModel.Name;
                user.EmailID = viewModel.EmailID;
                user.Skills = viewModel.SkillSets;
                user.TeamName = viewModel.TeamName;
                user.DOB = viewModel.DOB;
                user.ExtNumber = viewModel.CUGNumber;
                user.CSCJoiningDate = viewModel.CSCJoiningDate;
                user.ProjectJoiningDate = viewModel.ProjectJoiningDate;
                user.ManagerName = viewModel.ManagerName;
                user.Location = viewModel.Location;
                if (_repository.SaveChanges())
                {
                    return RedirectToAction("MyAccount", "Account");
                }
                else
                {
                    
                    return View(viewModel);
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.InnerException.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }

        }

        public ActionResult GetUserImage()
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                string uid = Session["UID"].ToString().Trim();
                UserTables user = _repository.users.Where(m => m.UserID == uid).FirstOrDefault();
                // 78 is the size of the OLE header for Northwind images
                byte[] image = user.ImageLocation;
                if (image!=null)
                {
                    ms.Write(image, 120, image.Length - 120);
                }
                else
                {
                    return File("~/Content/images/zurb.png", "image/jpeg");
                }
                return File(image, "image/jpeg");
            }
        }
        [HttpPost]
        public ActionResult SaveUserImage(HttpPostedFileBase image)
        {
            if (image != null)
            {
                //int b = Request.Files[0].ContentLength;
                //string a = Request.Files[0].ContentType;
                //byte[] ba = new byte[Request.Files[0].ContentLength];
                string uid = Session["UID"].ToString().Trim();
                UserTables user = _repository.users.Where(m => m.UserID == uid).FirstOrDefault();
                int length = image.ContentLength;
                byte[] buffer = new byte[length];
                image.InputStream.Read(buffer, 0, length);
                user.ImageLocation = buffer;
              
                //Save product to database 
                if (_repository.SaveChanges())
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    ms.Write(buffer, 120, buffer.Length - 120);
                    //return File(ms.ToArray(), "image/jpeg");
                    return File(ms.ToArray(), image.ContentType);
                }
                else
                {
                    return File("~/Content/images/zurb.png", "image/jpeg");
                }
            }
            else
            {
                return File("~/Content/images/zurb.png", "image/jpeg");
            }
        }
    }
}
